'''
@File    :   utils.py
@Time    :   2025/07/03 11:44:09
@Author  :   ZhangQifeng 
'''
import json
import os
from datetime import datetime, timedelta
from core.project_request import get
from core.logger import get_logger


log = get_logger(__name__)


def generate_time_ranges(start_date_str, interval_hours=1, interval_minutes=0, interval_seconds=0):
    # 初始化起始时间
    current_time = datetime.strptime(start_date_str, "%Y-%m-%d")
    
    result = []

    while True:
        # 计算结束时间
        begin_time = current_time
        end_time = begin_time + timedelta(
            hours=interval_hours,
            minutes=interval_minutes,
            seconds=interval_seconds
        )

        # 添加为元组 (字符串格式)
        result.append((
            begin_time.strftime("%Y-%m-%d %H:%M:%S"),
            end_time.strftime("%Y-%m-%d %H:%M:%S")
        ))

        # 更新 current_time 到下一个时间段的开始
        current_time = end_time

        # 当前段的开始时间和下一个段的开始时间不在同一天时停止
        if begin_time.day != current_time.day:
            break

    return result

def dict_to_json(in_dict):
    return json.dumps(in_dict,indent=4,ensure_ascii=False)

def download_img(
    img_url:str=None,
    output_dir:str="project_tag",
    user:str=None,
    id_card:str=None,
    img_type:str="png",
    show_img_log:bool=False
):
    """
    图片下载
    """
    if img_url is None or "":
        err = '图片地址不能为空'
        log.warning(err)
        return
    save_path = os.path.join("output","img",output_dir,user)
    os.makedirs(save_path, exist_ok=True)    
    img_file = os.path.join(save_path,f'{id_card}.{img_type}') if id_card else os.path.join(save_path,f'{user}.{img_type}')
    
    # 发送 GET 请求获取图片内容
    if show_img_log is False:
        get.disable_logging()
        
    response = get(img_url, stream=True)
    
    # 检查请求是否成功
    if response.status_code == 200:
        # 以二进制写入模式打开文件并保存图片
        with open(img_file, 'wb') as file:
            for chunk in response.iter_content(1024):  # 分块写入，避免大文件占用过多内存
                file.write(chunk)
    else:
        log.warning(f"无法下载，HTTP 状态码: {response.status_code}")


if __name__=='__main__':

    # 示例调用
    ranges = generate_time_ranges(start_date_str="2025-07-01", interval_hours=1)
    for r in ranges:
        print(r)